#include <Arduino.h>
#include <ch32v_def.h>
#include "spi_com.h"

uint32_t spi_getClkFreqInst(SPI_TypeDef *spi_inst)
{
    uint32_t spi_freq = SystemCoreClock;
    RCC_ClocksTypeDef RCC_ClocksStructure;
    switch ((uint32_t)spi_inst)
    {
#if defined(SPI1_BASE) || defined(SPI4_BASE) || defined(SPI5_BASE) || defined(SPI6_BASE)
#ifdef SPI1_BASE
    case SPI1_BASE:
#endif
#ifdef SPI4_BASE
    case SPI4_BASE:
#endif
#ifdef SPI5_BASE
    case SPI5_BASE:
#endif
#ifdef SPI6_BASE
    case SPI6_BASE:
#endif
        RCC_GetClocksFreq(&RCC_ClocksStructure);
        spi_freq = RCC_ClocksStructure.PCLK2_Frequency;
        break;
#endif
#if defined(SPI2_BASE) || defined(SPI3_BASE)
#ifdef SPI2_BASE
    case SPI2_BASE:
#endif
#ifdef SPI3_BASE
    case SPI3_BASE:
#endif
        RCC_GetClocksFreq(&RCC_ClocksStructure);
        spi_freq = RCC_ClocksStructure.PCLK1_Frequency;
        break;
#endif
    default:
        core_debug("CLK: SPI instance not set");
        break;
    }
    return spi_freq;
}

uint32_t spi_getClkFreq(spi_t *obj)
{
    SPI_TypeDef *spi_inst = NP;
    uint32_t spi_freq = SystemCoreClock;

    if (obj != NULL)
    {
        spi_inst = pinmap_peripheral(obj->pin_sclk, PinMap_SPI_SCLK);
        if (spi_inst != NP)
        {
            spi_freq = spi_getClkFreqInst(spi_inst);
        }
    }
    return spi_freq;
}

void spi_init(spi_t *obj, uint32_t speed, spi_mode_e mode, uint8_t msb)
{
    if (obj == NULL)
        return;

    uint32_t spi_freq = 0;
    uint32_t pull = 0;

    SPI_TypeDef *spi_mosi = pinmap_peripheral(obj->pin_mosi, PinMap_SPI_MOSI);
    SPI_TypeDef *spi_miso = pinmap_peripheral(obj->pin_miso, PinMap_SPI_MISO);
    SPI_TypeDef *spi_sclk = pinmap_peripheral(obj->pin_sclk, PinMap_SPI_SCLK);
    SPI_TypeDef *spi_ssel = pinmap_peripheral(obj->pin_ssel, PinMap_SPI_SSEL);

    if (spi_mosi == NP || spi_miso == NP || spi_sclk == NP)
    {
        core_debug("ERROR: at least one SPI pin has no peripheral\n");
        return;
    }

    SPI_TypeDef *spi_data = pinmap_merge_peripheral(spi_mosi, spi_miso);
    SPI_TypeDef *spi_cntl = pinmap_merge_peripheral(spi_sclk, spi_ssel);

    obj->spi = pinmap_merge_peripheral(spi_data, spi_cntl);

    if (spi_data == NP || spi_cntl == NP || obj->spi == NP)
    {
        core_debug("ERROR: SPI pins mismatch\n");
        return;
    }

    SPI_InitTypeDef SPI_InitStructure;

    switch ((uint32_t)obj->spi)
    {
    case SPI1_BASE:
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
        break;
    case SPI2_BASE:
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE);
        break;
    case SPI3_BASE:
        RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI3, ENABLE);
        break;
    }

    if (obj->pin_ssel != NC)
    {
        SPI_InitStructure.SPI_NSS = SPI_NSS_Hard;
    }
    else
    {
        SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
    }
    SPI_InitStructure.SPI_Mode = SPI_Mode_Master;

    spi_freq = spi_getClkFreqInst(obj->spi);
    if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV2_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV4_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV8_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV16_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_16;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV32_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV64_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_64;
    }
    else if (speed >= (spi_freq / SPI_SPEED_CLOCK_DIV128_MHZ))
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128;
    }
    else
    {
        SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256;
    }

    SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;

    if ((mode == SPI_MODE_0) || (mode == SPI_MODE_1))
        SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
    else
        SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;

    if ((mode == SPI_MODE_0) || (mode == SPI_MODE_2))
        SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
    else
        SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;

    if (msb == 0)
        SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_LSB;
    else
        SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;

    SPI_InitStructure.SPI_CRCPolynomial = 7;
    SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;

    pinmap_pinout(obj->pin_mosi, PinMap_SPI_MOSI);
    pinmap_pinout(obj->pin_miso, PinMap_SPI_MISO);
    pinmap_pinout(obj->pin_sclk, PinMap_SPI_SCLK);

    if (obj->pin_ssel != NC)
    {
        pinmap_pinout(obj->pin_sclk, PinMap_SPI_SSEL);
    }

    SPI_Init(obj->spi, &SPI_InitStructure);

    SPI_Cmd(obj->spi, ENABLE);
}

void spi_deinit(spi_t *obj)
{
    if (obj == NULL)
        return;
    SPI_Cmd(obj->spi, DISABLE);
    SPI_I2S_DeInit(obj->spi);
}

spi_status_e spi_send(spi_t *obj, uint8_t *Data, uint16_t len, uint32_t Timeout)
{
    return spi_transfer(obj, Data, Data, len, Timeout, 1);
}

spi_status_e spi_transfer(spi_t *obj, uint8_t *tx_buffer, uint8_t *rx_buffer, uint16_t len, uint32_t Timeout, bool skipReceive)
{
    spi_status_e ret = SPI_OK;
    uint32_t tickstart, size = len;

    if ((obj == NULL) || (len == 0) || (Timeout == 0U))
    {
        return Timeout > 0U ? SPI_ERROR : SPI_TIMEOUT;
    }
    tickstart = getCurrentMillis();

    while (size--)
    {
        while (SPI_I2S_GetFlagStatus(obj->spi, SPI_I2S_FLAG_TXE) == RESET)
            ;
        SPI_I2S_SendData(obj->spi, *tx_buffer++);

        if (!skipReceive)
        {
            while (SPI_I2S_GetFlagStatus(obj->spi, SPI_I2S_FLAG_RXNE) == RESET)
                ;
            *rx_buffer++ = SPI_I2S_ReceiveData(obj->spi);
        }

        if ((Timeout != 0xFFFFFFFFU) && (getCurrentMillis() - tickstart >= Timeout))
        {
            ret = SPI_TIMEOUT;
            break;
        }
    }
    return ret;
}
